<template>
  <div class="user-info">
    <el-card>
      <h2>个人信息</h2>
      <el-avatar :size="80" :src="avatar" />
      <el-input v-model="name" placeholder="请输入姓名" class="mt" disabled />
      <el-button class="mt" type="primary" @click="dialogVisible = true">
        修改密码
      </el-button>
    </el-card>

    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改密码"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="原密码">
          <el-input type="password" v-model="form.oldPwd" autocomplete="off" />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input type="password" v-model="form.newPwd" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input
            type="password"
            v-model="form.confirmPwd"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePassword">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { updateUserPassword } from '@/api/user' // 你需要自己实现api接口调用

const router = useRouter()
const userStore = useUserStore()

const avatar = ref(
  'https://img.qimai.cn/appicon/1209522077/aec3f24aa26264270d1f9f061d4e45c7_256.png'
)
const name = computed(() => userStore.userInfo.username || '')

const dialogVisible = ref(false)
const form = ref({
  oldPwd: '',
  newPwd: '',
  confirmPwd: '',
})

async function updatePassword() {
  if (form.value.newPwd !== form.value.confirmPwd) {
    ElMessage.error('新密码与确认密码不一致')
    return
  }
  if (!form.value.oldPwd || !form.value.newPwd) {
    ElMessage.warning('请填写完整密码信息')
    return
  }

  try {
    const res = await updateUserPassword({
      user_id: userStore.userInfo.id,
      old_password: form.value.oldPwd,
      new_password: form.value.newPwd,
    })

    if (res.code === 0) {
      ElMessage.success('密码修改成功，即将退出登录')
      dialogVisible.value = false
      form.value = { oldPwd: '', newPwd: '', confirmPwd: '' }

      userStore.logout()
      router.push('/')
    } else {
      ElMessage.error(res.message || '密码修改失败')
    }
  } catch (error) {
    ElMessage.error('网络或服务器错误')
  }
}
</script>

<style scoped>
.mt {
  margin-top: 20px;
}
.user-info {
  max-width: 480px;
  margin: 30px auto;
}
</style>
